using System;
using System.Drawing;
using System.IO;
using System.Web;
using System.Linq;

namespace Sherwood.Imaging.Providers
{
    public class UrlImageProvider : IImageProvider
    {
        private readonly IStringProvider _rootPath;
        public IStringProvider UrlProvider { get; set; }

        public UrlImageProvider(IStringProvider urlProvider, string rootPath) 
            : this(urlProvider, new StaticStringProvider(rootPath))
        {
        }

        public UrlImageProvider(IStringProvider urlProvider, IStringProvider rootPath)
        {
            _rootPath = rootPath;
            UrlProvider = urlProvider;
        }

        public Image GetImage()
        {
            var url = UrlProvider.GetString();

            Uri uri;
            if (Uri.TryCreate(url, UriKind.Absolute, out uri) && uri.IsFile)
                return Image.FromFile(url);

            var useAnyExtension = url.EndsWith(".*");
            if (useAnyExtension)
                url = url.Substring(0, url.Length - 2);

            string path = HttpContext.Current.Server.MapPath(url);
            var rootPath = _rootPath == null ? null : _rootPath.GetString();
            if (!string.IsNullOrEmpty(rootPath))
            {
                var appRoot = HttpContext.Current.Server.MapPath("/");
                var physicalRoot = Path.Combine(appRoot, rootPath) + Path.DirectorySeparatorChar;
                path = Path.GetFullPath(physicalRoot + path.Substring(appRoot.Length));
            }
            if (useAnyExtension)
                path = Directory.GetFiles(Path.GetDirectoryName(path), Path.GetFileName(path) + ".*").FirstOrDefault() ?? path;
            return Image.FromFile(path);
        }
    }
}